import { Form, Button, InputNumber, Input, Alert } from 'antd';
import React, { Fragment, useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import _ from 'lodash';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';
import { acceptConfig } from './ScoreTemplate.js'

const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

const ScoreFormItem = (props) => {
  console.log(props);
  return (
    <Form.Item
      label={props.label}
      name={props.sort}
      initialValue={props.init_value}
      rules={props.rules}
    >
      <InputNumber min={props.custom_field.min_score} max={props.custom_field.max_score} />
      <Alert message={`智能提示：${props.custom_field.remark}`} type="info" style={{height: '32px', marginTop: '5px'}} />
    </Form.Item>
  )
}

const LongTextFormItem = (props) => {
  return (
    <Form.Item
      label={props.label}
      name={props.sort}
      initialValue={props.init_value}
      rules={props.rules}
    >
      <Input.TextArea placeholder={props.custom_field.placeholder} autoSize={{ minRows: 3, maxRows: 6 }} />
    </Form.Item>
  )
}

const PageContent = () => {
  const [formConfig, setFormConfig] = useState({});

  useEffect(() => {
    // 拿配置
    if (!formConfig.id) {
      setFormConfig(acceptConfig);
    }
  }, [formConfig]);

  const submitHandle = (values) => {
    console.log('提交:', values);
    // 遍历formConfig.item_list，找值回传给value
    _.map(formConfig.item_list, (item) => {
      if (values[item.sort] !== undefined && values[item.sort] !== null) {
        item.value = values[item.sort];
      }
    });
    console.log(formConfig.item_list);
  };
  console.log(formConfig);
  return (
    <PageContainer>
      <Form
        labelCol={{span: 8}}
        wrapperCol={{span:16}}
        name="basic"
        onFinish={submitHandle}
      >
        {
          (formConfig.item_list && formConfig.item_list.length) && 
          <>
            {
              formConfig.item_list.map((item) => (
                <Fragment key={item.sort}>
                  {
                    item.type === 'score' &&
                    <ScoreFormItem {...item}/>
                  }
                  {
                    item.type === 'long_text' &&
                    <LongTextFormItem {...item}/>
                  }
                </Fragment>
              ))
            }
          </>
        }

        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
          <Button 
            style={{marginLeft: '10px'}}
            htmlType="button" 
            onClick={() => {
              console.log('cancel');
            }}
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </PageContainer>
  );
};

export default PageContent;
